#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <arpa/inet.h>

#define MAX_BUF 1024
#define PORT 7575
#define BACKLOG 5

int main() {
    int socket_fd, new_fd;
    socklen_t addr_len;
    struct sockaddr_in server_addr, client_addr;
    char buffer[MAX_BUF];
    
    // 创建socket
    if ((socket_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
        perror("socket creation failed");
        exit(EXIT_FAILURE);
    }
    
    // 配置服务器地址
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(PORT);
    server_addr.sin_addr.s_addr = INADDR_ANY;  // 监听所有网络接口
    
    // 绑定socket
    if (bind(socket_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {
        perror("bind failed");
        close(socket_fd);
        exit(EXIT_FAILURE);
    }
    
    // 开始监听
    if (listen(socket_fd, BACKLOG) == -1) {
        perror("listen failed");
        close(socket_fd);
        exit(EXIT_FAILURE);
    }
    
    printf("Server listening on port %d...\n", PORT);
    
    while(1) {
        printf("run");
        // 接受客户端连接
        addr_len = sizeof(client_addr);
        if ((new_fd = accept(socket_fd, (struct sockaddr *)&client_addr, &addr_len)) == -1) {
            perror("accept failed");
            continue;  // 继续等待其他连接
        }
        
        // 获取客户端IP地址
        char client_ip[INET_ADDRSTRLEN];
        inet_ntop(AF_INET, &(client_addr.sin_addr), client_ip, INET_ADDRSTRLEN);
        printf("Client connected from %s:%d\n", client_ip, ntohs(client_addr.sin_port));
        
        // 创建子进程处理客户端请求
        pid_t pid = fork();
        if (pid < 0) {
            perror("fork failed");
            close(new_fd);
            continue;
        }
        
        if (pid == 0) {  // 子进程
            close(socket_fd);  // 子进程不需要监听socket
            
            // 接收客户端数据
            ssize_t bytes_received;
            // 阻塞在recv函数
            while ((bytes_received = recv(new_fd, buffer, MAX_BUF - 1, 0)) > 0) {
                buffer[bytes_received] = '\0';  // 确保字符串终止
                printf("Received from %s: %s\n", client_ip, buffer);
                
                // 回显给客户端
                if (send(new_fd, buffer, bytes_received, 0) == -1) {
                    perror("send failed");
                    break;
                }
            }
            
            if (bytes_received == 0) {
                printf("Client %s disconnected\n", client_ip);
            } else if (bytes_received == -1) {
                perror("recv failed");
            }
            
            close(new_fd);
            exit(EXIT_SUCCESS);  // 子进程退出
        } else {  // 父进程
            close(new_fd);  // 父进程不需要客户端socket
        }
    }
    
    close(socket_fd);
    return 0;
}
